<!--
 * @Author: Xiaochuan-W
 * @Github:
 * @Date: 2021-09-13 17:35:28
 * @LastEditors: Xiaochuan-W
 * @LastEditTime: 2024-08-08 16:30:16
-->
<template>
	<div ref="editor" :style="{ width: width, height: height }" />
</template>

<script setup lang="ts">
import {ref,onMounted,onUpdated,watch} from 'vue'
import ace from 'ace-builds';
// import 'ace-builds/webpack-resolver';
import 'ace-builds/src-noconflict/mode-yaml';
import 'ace-builds/src-noconflict/mode-sql';
import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/mode-markdown';
import 'ace-builds/src-noconflict/mode-java';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/worker-yaml';
import 'ace-builds/src-noconflict/worker-javascript';
import 'ace-builds/src-noconflict/theme-chrome';

const emit = defineEmits(['update:modelValue']);
const props = defineProps({
	modelValue: {
		type: String,
		default:''
	},
	readonly: {
		type: Boolean,
		default: false
	},
	theme: {
		type: String,
		default: 'chrome'
	},
	mode: {
		type: String,
		default: 'javascript'
	},
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '100%'
	},
	gutter:{
		type: Boolean,
		default: true
	},
});
const editor = ref<any>();
let position = { row: 0, column: 0 };
let aceEditor: any = null;
const initEditor = () => {
	if (aceEditor) {
		// 实例销毁
		aceEditor.destroy();
	}
	aceEditor = ace.edit(editor.value, {
		fontSize: 12,
		fontFamily: 'Consolas,Monaco,monospace',
		theme: `ace/theme/${props.theme}`, // dracula
		mode: `ace/mode/${props.mode}`,
		useWorker: false,
		showPrintMargin: false, // 去掉中间竖线
		showGutter: props.gutter, // 显示行号
		tabSize: 2,
		useSoftTabs: true,
		readOnly: props.readonly
	});
	aceEditor.setOptions({
		autoScrollEditorIntoView: true,
		copyWithEmptySelection: true
	});
	aceEditor.on('blur', () => {
		position = aceEditor.selection.getCursor();
		emit('update:modelValue', aceEditor.getValue());
	});
	aceEditor.alignCursors();
	aceEditor.getSession().setUseWrapMode(true);
	aceEditor.setOption('wrap', 'off');
	aceEditor.setValue(props.modelValue, -1);
	aceEditor.resize();
};
const getContent = () => {
	return aceEditor.getValue();
};
const setContent = (val: any) => {
	aceEditor.setValue(val, -1);
};
defineExpose({ getContent, setContent, aceEditor });
onMounted(() => {
	initEditor();
});
onUpdated(() => {
	editor.value.style.fontSize = '12px';
});
// watch(
// 	() => props.insert,
// 	() => {
// 		if (props.insert) {
// 			aceEditor.focus();
// 			aceEditor.gotoLine(position.row + 1, position.column);
// 			aceEditor.insert(props.insert);
// 		}
// 	}
// );
watch(
	() => props.modelValue,
	(newVal) => {
		aceEditor.setValue(newVal, -1);
	}
);
// aceEditor.selection.getCursor();//获取当前光标所在行列
// aceEditor.gotoLine(1, 1);//光标跳转到x行x列
// aceEditor.insert("hello");//插入文本
</script>

<style lang="scss" scoped>
:deep(.ace_content) {
	padding-bottom: 20px !important;
}
</style>
